package com.itjiange.shopsystem.adapter;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.itjiange.shopsystem.pojo.UserInfo;
import com.itjiange.shopsystem.service.UserService;
import com.itjiange.shopsystem.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

/**
 * 第三方登录的适配器角色
 *
 * @author ItJiange
 * @date 2023/11/19
 */
@Slf4j
@Component
public class Login3rdAdapter extends UserService implements Login3rdTarget {

    @Value("${gitee.state}")
    private String giteeState;
    @Value("${gitee.user.url}")
    private String giteeUserUrl;
    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;
    @Value("${gitee.token.url}")
    private String giteeTokenUrl;

    /**
     * gitee 授权登录
     * @param code
     * @param state
     * @return
     */
    @Override
    public String loginByGitee(String code, String state) {
        if (!giteeState.equals(state)) {
            throw new RuntimeException("state ERROR");
        }
        // 发送请求获取 token
        String tokenUrl = giteeTokenUrl.concat(code);
        JSONObject tokenResponse = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
        log.info("token: {}", tokenResponse.toJSONString());
        // 获取 accessToken
        String accessToken = String.valueOf(tokenResponse.get("access_token"));
        // 获取用户信息
        String userUrl = giteeUserUrl.concat(accessToken);
        JSONObject userInfoResponse = HttpClientUtils.execute(userUrl, HttpMethod.GET);
        log.info("userInfo: {}", userInfoResponse.toJSONString());
        // 将 gitee@name 作为用户名，将 name 作为密码
        String name = String.valueOf(userInfoResponse.get("name"));
        String userName = giteeUserPrefix.concat(name);
        String password = name;
        return autoRegisterLogin3rd(userName, password);
    }

    /**
     * 自动登录及注册
     * @param userName
     * @param password
     * @return
     */
    private String autoRegisterLogin3rd(String userName, String password) {
        // 如果第三方账号已经注册过，则直接登录
        if (super.checkUserExists(userName)) {
            return super.login(userName, password);
        }
        // 注册
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userInfo.setCreateDate(new Date());
        // 先注册后登陆
        super.register(userInfo);
        return super.login(userName, password);
    }

    @Override
    public String loginByWechat(String... params) {
        return null;
    }

    @Override
    public String loginByQQ(String... params) {
        return null;
    }
}
